import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { parseIdentity, refreshToken } from '@/api/auth'

export const useAuthStore = defineStore(
  'sv-auth',
  () => {
    const access_token = ref('') // 访问令牌
    const refresh_token = ref('') // 刷新令牌

    // 身份信息
    const identity = ref({
      id: '',
      username: '',
      roles: [],
      permissions: []
    })

    function clearIdentity() {
      identity.value = {}
    }

    function clearToken() {
      access_token.value = ''
      refresh_token.value = ''
    }

    // 静默刷新token
    async function refreshTokenSilence() {
      const tokenRes = await refreshToken({
        access_token: access_token.value,
        refresh_token: refresh_token.value
      })
      access_token.value = tokenRes.access_token
      refresh_token.value = tokenRes.refresh_token

      // 再更新身份信息
      const identityRes = await parseIdentity({
        id: identity.value.id,
        username: identity.value.username
      })
      identity.value = identityRes.data
    }

    // 路由菜单禁止持久化
    const menuFlat = ref([]) // 扁平菜单（禁止持久化）
    const menuFlatRaw = ref([]) // 扁平原菜单（禁止持久化）
    const menuTree = ref([]) // 树形菜单（禁止持久化）
    const menuTreeRaw = ref([]) // 树形原菜单（禁止持久化）

    function clearMenu() {
      menuFlat.value = []
      menuFlatRaw.value = []
      menuTree.value = []
      menuTreeRaw.value = []
    }

    return {
      access_token,
      refresh_token,
      identity,
      clearIdentity,
      clearToken,
      refreshTokenSilence,
      menuFlat,
      menuFlatRaw,
      menuTree,
      menuTreeRaw,
      clearMenu
    }
  },
  {
    persist: {
      pick: ['access_token', 'refresh_token', 'identity']
    }
  }
)
